import OrderList from '@/components/school/orderList';
import UvUpload from '@/components/school/uv-upload';
import {mapGetters} from "vuex";
import * as OrderApi from '@/api/school/order.js';
import * as TaskInfoApi from '@/api/school/taskInfo.js';
import diyJson from '@/config/diy.js';
import * as MemerApi from '@/api/member/user.js';
import {AgreementEnum,} from '@/utils/dict.js';

export const mixins =
    {
      computed: mapGetters(['uid', 'userInfo', 'shareInfo', 'schoolId']),
      components: {
        UvUpload,
        OrderList,
      },
      data() {
        return {
          datetimePicker: {
            value: '',
            minDate: Number(new Date()),
            maxDate: Number(new Date().setHours(new Date().getMinutes() + 24)),
          },

          deliveryDatetimePicker: {
            value: '',
            minDate: Number(new Date().getTime() + (30 * 60 * 1000)),
            maxDate: Number(new Date().getTime() + (24 * 60 * 60 * 1000)),
            // 期望送达时间回显值
            deliveryTimeValue: '',
            deliveryTimeField: '',
          },

          dateTime: [
            {
              "label": "",
              "value": "06:00~07:00"
            },
            {
              "label": "",
              "value": "07:00~08:00"
            }
            ,
            {
              "label": "",
              "value": "08:00~09:00"
            }
            ,
            {
              "label": "",
              "value": "09:00~10:00"
            }
            ,
            {
              "label": "",
              "value": "10:00~11:00"
            }
            ,
            {
              "label": "",
              "value": "11:00~12:00"
            },
            {
              "label": "",
              "value": "11:30~12:30"
            },
            {
              "label": "",
              "value": "12:00~13:00"
            },
            {
              "label": "",
              "value": "13:00~14:00"
            }
            ,
            {
              "label": "",
              "value": "14:00~15:00"
            }
            ,
            {
              "label": "",
              "value": "15:00~16:00"
            }
            ,
            {
              "label": "",
              "value": "16:00~17:00"
            }
            ,
            {
              "label": "",
              "value": "18:00~19:00"
            },
            {
              "label": "",
              "value": "20:00~21:00"
            },
            {
              "label": "",
              "value": "22:00~23:00"
            },
            {
              "label": "",
              "value": "23:00~24:00"
            }
          ],

          rules: {
            'content': {
              type: 'string',
              required: true,
              message: '请填写你的订单备注',
              trigger: ['blur', 'change']
            }
            , 'expireTime': {
              type: 'string',
              required: true,
              message: '请选择',
              trigger: ['blur', 'change']
            },
            'actionAddress': {
              type: 'string',
              required: true,
              message: '请填始发地',
              trigger: ['blur', 'change']
            }, 'destination': {
              type: 'string',
              required: true,
              message: '请填始目的地',
              trigger: ['blur', 'change']
            }, 'amount': {
              type: 'number',
              required: true,
              message: '金额不能为空',
              trigger: ['blur', 'change']
            }, 'phone': {
              type: 'number',
              required: true,
              message: '联系电话不能为空',
              trigger: ['blur', 'change']
            },
          },

          taskInfoGoods: {
            mainPic: []
          },

          btnDisabled: false,

          themConfig: diyJson.commonStyle,

          pageBody: {
            pageMargin: 12,
            paddingBottom: 65,
          },

          isReadAggreement: [],
          photos: [],
          form: {
            isRead: false,
            taskId: '',
            skuName: '',
            skuId: '',
            num: 1,
            salesPrice: 1,
            errandChargeAmount: 2,
            needAudit: false,
            expireTime: '',
            serviceFee: 0,
            amount: 1,
            phone: undefined,
            content: '',
            sensitiveContent: '',
            actionAddress: '',
            destination: undefined,
            photos: [],
            shareCode: '',
            expectedDeliveryTimeStart: '',
            expectedDeliveryTimeEnd: ''
          },
          // 1=目的地，2=始发地
          useAddressType: 2,
          useAddress: [],
          useAddressData: [],
          currentFormField: 'content',
          deliveryTimes: [
            {
              name: '1小时候后',
              value: 3,
            },
            {
              name: '2小时候后',
              value: 2,
            },
            {
              name: '3小时候后',
              value: 3,
            },
            {
              name: '4小时候后',
              value: 4,
            },
            {
              name: '5小时候后',
              value: 5,
            },
            {
              name: '6小时候后',
              value: 6,
            },
            {
              name: '7小时候后',
              value: 7,
            },
            {
              name: '8小时候后',
              value: 8,
            }
          ]
        };
      },
      created() {

      },
      onLoad: function (options) {
        let p = options.params;
          // console.log("params",p)
        if (p) {
          let params = JSON.parse(decodeURIComponent(p));
          this.form.taskId = params.taskId;
          this.form.taskCode = params.taskCode;
          this.form.salesPrice = params.salesPrice;
          this.form.num = params.num;
          this.form.skuId = params.skuId;
          this.form.skuName = params.skuName;
        }
        this.form.phone = this.userInfo.phone;
        let form = {...this.form};
        form['phone'] = this.userInfo.phone;
        this.form = form;

        this.initData();
        this.getUseAddressData();
      },

      onHide() {
        // 不知道为什么每次切换app 收货地址 和手机号 总是被初始值覆盖
        // if (this.form.destination) {
        //   localStorage.setItem('form.destination', this.form.destination);
        // }
        // if (this.form.phone) {
        //   localStorage.setItem('form.phone', this.form.phone);
        // }
        // uni.showToast({
        //   title: "onHide  "+this.form.destination
        // })
      },
      onShow() {
        //  let destination = localStorage.getItem('form.destination');
        //  if (destination) {
        //    this.form.destination = destination;
        //  }
        //  let phone = localStorage.getItem('form.phone');
        //  if (phone) {
        //    this.phone = phone;
        //  }
        // uni.showToast({
        //   title: "onShow  "+phone
        // })


      },
      mounted() {

      },

      methods: {

        async initData() {
          this.getTaskDetail(this.form.taskCode, this.schoolId).then(res => {
          });
        },

        async getTaskDetail(taskCode, schoolId) {
          let that = this;
          return new Promise(() => {
            TaskInfoApi.getTaskByCode(taskCode, schoolId).then(res => {
              that.taskInfoGoods = res.data;
              that.form.amount = res.data.salePrice;
              that.form.errandChargeAmount = res.data.errandChargeAmount;
            })
          });
        },

        // 打开时间选择框
        openDatePick() {
          this.$refs.datetimePicker.open();
        },

        confirmDeliveryTime(e) {
          var date = new Date(e.value);
          let day = ('0' + date.getDate()).slice(-2) + '日';
          var hours = ('0' + date.getHours()).slice(-2);
          var minutes = ('0' + date.getMinutes()).slice(-2);

          this.deliveryDatetimePicker[this.deliveryDatetimePicker.deliveryTimeField] = e.value;
          this.form[this.deliveryDatetimePicker.deliveryTimeField] = day + hours
              + ':' + minutes;
        },

        showTime(field) {
          // console.log("ss",field);
          this.deliveryDatetimePicker.deliveryTimeField = field;
          this.$refs.deliveryTimePicker.open();
        },

        dateTimePickerfilter(type, options) {
          return options;
        },

        // 选择时间回调
        timestampConvertYYYY(e) {
          // console.log("时间",new Date(e.value));

          var date = new Date(e.value); // 转换为Date对象

          // 获取年月日时分秒
          var year = date.getFullYear();
          var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
          var day = ('0' + date.getDate()).slice(-2);
          var hours = ('0' + date.getHours()).slice(-2);
          var minutes = ('0' + date.getMinutes()).slice(-2);
          // var seconds = ('0' + date.getSeconds()).slice(-2);
          return `${year}-${month}-${day} ${hours}:${minutes}:00`;
        },

        datePickerformatter(type, value) {
          if (type === 'year') {
            return `${value}年`
          }
          if (type === 'month') {
            return `${value}月`
          }
          if (type === 'day') {
            return `${value}日`
          }

          if (type === 'hour') {
            return `${value}点`
          }

          if (type === 'minute') {
            return `${value}分`
          }
          return value
        },

        // 快捷选择时间
        setExpireTime(v) {
          let d = new Date();
          if (v < 1) {
            d.setMinutes(d.getMinutes() + (v * 60));
          } else {
            d.setHours(d.getHours() + v);
          }
          let yyyyMMdd = this.timestampConvertYYYY({value: Number(d)});

          // 组合成 yyyy-mm-dd HH:mm:ss 格式
          this.form.expireTime = yyyyMMdd;
        },

        clearShareCode() {
          this.shareInfo = null;
          this.$store.commit('SET_SHARE_CODE', null);
        },

        closeFormPopup() {
          if (this.currentFormField === 'expectedDeliveryTime') {
            if (this.deliveryDatetimePicker.expectedDeliveryTimeStart
                && this.deliveryDatetimePicker.expectedDeliveryTimeEnd) {
              if (this.deliveryDatetimePicker.expectedDeliveryTimeStart
                  > this.deliveryDatetimePicker.expectedDeliveryTimeEnd) {
                uni.showToast({
                  title: '开始时间不能小于结束时间',
                  icon: 'none',
                  duration: 2000
                });
                return;
              }
              this.form.deliveryTimeStart = this.timestampConvertYYYY(
                  {value: this.deliveryDatetimePicker.expectedDeliveryTimeStart})
              this.form.deliveryTimeEnd = this.timestampConvertYYYY(
                  {value: this.deliveryDatetimePicker.expectedDeliveryTimeEnd})
            }

          }
          this.$refs.formPopup.close();
        },

        openInput(formKey) {
          this.currentFormField = formKey;
          this.$refs.formPopup.open();
        },

        // 获取常用地址
        getUseAddressData() {
          MemerApi.getUseAddress({}).then(res => {
            this.useAddressData = res.data;
            if (res.data.length > 0) {
              if (!this.form.destination) {
                this.form.destination = res.data[0].addressVos[0].detail
              }
              if (!this.form.actionAddress) {
                this.form.actionAddress = res.data[1].addressVos[0].detail
              }
            }
          })
        },

        // 选择常用地址
        selectUseAddress(type) {
          this.useAddressType = type;
          for (let i = 0; i < this.useAddressData.length; i++) {
            let item = this.useAddressData[i];
            if (item.type === type) {
              let arr = [];
              for (let j = 0; j < item.addressVos.length; j++) {
                arr.push(item.addressVos[j].detail)
              }
              this.useAddress = [arr];
              this.$refs.picker.open();
              return;
            }
          }
        },

        // 确定常用地址
        useAddressConfirm(e) {
          console.log("常用地址", e);
          if (this.useAddressType === 2) {
            this.form.actionAddress = e.value[0];
          } else {
            this.form.destination = e.value[0];
          }
        },

        // 输入金额变化
        amountInputChange(e) {
          this.$nextTick(() => {
            let amount = parseFloat(e).toFixed(2);
            this.form.amount = amount + this.taskInfoGoods.salePrice;
            this.form.serviceFee = parseFloat(amount);
            this.form.amount = parseFloat(amount)
                + this.taskInfoGoods.salePrice;
          });
          console.log("amount", this.form.amount)
        },

        // 选择常用金额
        useAmount(e) {
          this.form.serviceFee = e;
          this.form.amount = e + this.taskInfoGoods.salePrice;
        },

        agreementReadClick(e) {
          this.form.isRead = e;
        },

        /**
         * 上传结果
         * @param array [
         *   {
         *     images:[{'url':''}],
         *     params:'',
         *   }
         * ]
         */
        uploadSuccess(array) {
          console.log("array", array)
          let photos = [];
          for (let i = 0; i < array.images.length; i++) {
            photos.push(array.images[i].url);
          }
          this.form.photos = photos;
          console.log("form", this.form)
        },

        // 提交表单
        submit() {

          console.log("form", this.form)

          if (!this.form.isRead) {
            this.$refs.notify.show({
              message: '请阅读协议声明',
              type: 'warning',
              duration: 1000,
              safeAreaInsetTop: true
            });
            return;
          }
          this.setExpireTime(24);
          // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true


          this.btnDisabled = true;

          // 邀请码
          if (this.shareInfo !== undefined && this.shareInfo !== null
              && this.shareInfo !== '') {
            this.form['inviteCode'] = JSON.parse(this.shareInfo).code
          }

          if (this.form.content === null || this.form.content === ''
              || this.form.actionAddress === null || this.form.actionAddress
              === ''
          ) {
            uni.showToast({
              title: '请填写您的跑腿需求',
              icon: 'none'
            });
            this.btnDisabled = false;
            return;
          }

          if (this.form.destination === null || this.form.destination === '') {
            uni.showToast({
              title: '请填写您的收货地址',
              icon: 'none'
            });
            this.btnDisabled = false;
            return;
          }

          if (this.form.taskCode === 'TASK02' && this.form.sensitiveContent
              == '') {
            uni.showToast({
              title: '请填写取件码',
              icon: 'none'
            });
            this.btnDisabled = false;
            return;
          }

          // let payAmount = this.form.serviceFee + this.taskInfoGoods.salePrice;
          let payAmount = (this.form.serviceFee) + (this.form.salesPrice
              * this.form.num) + this.form.errandChargeAmount
          let form = {
            ...this.form
            , schoolId: this.schoolId
          }
          form.amount = payAmount;

          OrderApi.createOrder(form).then(res => {

            let data = res.data;
            let params = {
              outTradeNo: data.outTradeNo,
              amount: data.amount,
              body: this.taskInfoGoods.taskName,
              payScene: data.payScene
            }

            this.$refs.notify.show({
              message: '正在跳转支付',
              type: 'success',
              duration: 1000,
              safeAreaInsetTop: true
            });

            this.$store.commit('SET_JUMP_INFO', params);

            setTimeout(() => {
              this.btnDisabled = false;
              uni.navigateTo({
                url: `/pages/school/pay/index?params=${encodeURIComponent(JSON.stringify(params))}`
              })
            }, 1000)
          }).catch(e => {
            this.btnDisabled = false;
          })
        },

        readAgreement() {
          uni.navigateTo({
            url: `/pages/users/privacy/index?params=${encodeURIComponent(
                JSON.stringify(AgreementEnum.pushTask))}`
          })
        },
      },
      onReachBottom() {

      }
    }
